#include "music.hpp"

#include <iostream>

Music::Music()
{
	emu = NULL;
}

Music::~Music()
{
}

#include "gme.h"
#include "SDL_mixer.h"

void MusicFunc(void *emu, Uint8 *stream, int len)
{
	// correct only on little-endian
	gme_play((Music_Emu*)emu, len / sizeof(short), (short*)stream);
}

#include "audio.hpp"
#include "disk.hpp"

bool Music::Open(std::string & name)
{
	return Open(name.c_str());
}

bool Music::Open(const char *name)
{
	const char *DIR = "snd/";
	const char *EXT = ".gbs";

	std::string filename (DIR);
	filename += name;
	filename += EXT;

	std::string text;
	int readct = Dsk.TextOpen(filename, text);
	if (readct <= 0)
		return false;

	gme_err_t err = gme_open_data(text.c_str(), text.size(), &emu, 
					Aud.Freq());

	if (err)
	{
		std::cerr << "Music::Open(" << name << "): " << err;
		std::cerr << std::endl;
		return false;
	}
	
	gme_mute_voices(emu, 0);
	return true;
}

void Music::Close()
{
	Stop();
	gme_delete(emu);
	emu = NULL;
}

void Music::Play(int track)
{
	if (!emu)
		return;

	gme_start_track(emu, track);
	Resume();
}

void Music::Resume()
{
	if (emu)
		Mix_HookMusic(&MusicFunc, emu);
}

void Music::Stop()
{
	Mix_HookMusic(NULL, NULL);
}

void Music::Fade(int time)
{
	if (emu)
		gme_set_fade(emu, gme_tell(emu));
}

Music Mus;
